from django.utils.translation import gettext_lazy as _

from chatbot.bot import conf
from chatbot.bot.domain.initialization import Initialization
from chatbot.bot.engine import ChatBot
from chatbot.models import Tenant, ChatVisitor, ChatLog, ChatSession


def get_chat_box_initialization(session):
    init_info = Initialization()
    init_info.session_id = session.session_id

    tenant: Tenant = session.bot.tenant

    init_info.tenant_info.tenant_id = tenant.id
    init_info.tenant_info.name = tenant.name
    init_info.tenant_info.logo = tenant.logo.url
    init_info.tenant_info.url = tenant.url
    init_info.tenant_info.profile = ''

    visitor: ChatVisitor = session.visitor
    init_info.visitor_info.name = visitor.username if visitor.username else _('Unknown')
    init_info.visitor_info.avatar = visitor.avatar.url if visitor.avatar else conf.BOT_VISITOR_AVATAR
    init_info.visitor_info.id = visitor.id

    chat_sessions = ChatSession.objects.order_by('-start_time')
    if len(chat_sessions):
        chat_logs = ChatLog.objects.filter(chat_session=chat_sessions[0])
    else:
        chat_logs = []

    init_info.history_messages = chat_logs

    bot: ChatBot = session.bot
    init_info.language = bot.language
    init_info.robot_info.avatar = bot.avatar,
    init_info.robot_info.name = bot.name

    greeting_info = bot.greeting_info()
    init_info.greetings = greeting_info.get(conf.SCRIPT_GREETING)
    init_info.greeting_recommend_info['recommend_script'] = greeting_info.get(
        conf.SCRIPT_GREETING_QUESTION_RECOMMEND_GUIDING)
    init_info.greeting_recommend_info['questions'] = greeting_info.get(conf.SCRIPT_GREETING_RECOMMEND_QUESTION)

    return init_info
